package com.thymeleaf.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thymeleaf.demo.entity.User;
import com.thymeleaf.demo.service.UserService;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author : niceyoo
 * @version : 1.0
 * @title : UserController.java
 * @description : user表控制层
 * @copyright : 公共服务与应急管理战略本部 Copyright(c)2020
 * @date : 2021/7/15 14:32
 */
@RestController
@RequestMapping("user")
public class UserController extends ApiController {

    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 用户列表展示
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    @GetMapping("view")
    public ModelAndView view(){
        return new ModelAndView("/user").addObject("modelName","用户管理模块");
    }

    /**
     * 新增用户
     *
     * @param user 用户实体
     * @return 新增结果
     */
    @PostMapping("insert")
    public R insert(@RequestBody User user){
        Assert.notNull(user,"user不能为空");
        return success(userService.save(user));
    }

    /**
     * 修改用户
     *
     * @param user 用户实体
     * @return 修改结果
     */
    @PostMapping("update")
    public R update(@RequestBody User user){
        Assert.notNull(user,"user不能为空");
        return success(userService.saveOrUpdate(user));
    }

    /**
     * 删除用户
     *
     * @param ids 用户ids
     * @return 删除结果
     */
    @PostMapping("delete")
    public R delete(@RequestParam List<String> ids){
        Assert.notNull(ids,"ids不能为空");
        return success(userService.removeByIds(ids));
    }

    /**
     * 查询用户数据 - 分页
     *
     * @param current 当前页
     * @param size 页码大小
     * @return 分页数据列表
     */
    @GetMapping("selectAll")
    public R selectAll(@RequestParam Integer current, @RequestParam Integer size, @RequestParam(required = false) String userName){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.hasText(userName)){
            queryWrapper.like("user_name", userName);
        }
        Page<User> page = new Page<User>(current,size);
        IPage<User> result = userService.page(page, queryWrapper);
        return success(result);
    }
}
